package yyds.sniarbtej.transformer.intellij;

import org.objectweb.asm.Opcodes;
import org.objectweb.asm.tree.*;
import yyds.sniarbtej.transformer.BaseClassTransformer;
import yyds.sniarbtej.transformer.ClassRewriter;

public final class Decrypt extends BaseClassTransformer {
    public String canTransformClassName() {
        return "java/math/BigInteger";
    }

    public byte[] rewrite(byte[] in) {
        return transform(in, new ClassRewriter() {
            @Override
            public void rewriteMethod(MethodNode node) {
                if ("oddModPow".equals(node.name) && "(Ljava/math/BigInteger;Ljava/math/BigInteger;)Ljava/math/BigInteger;".equals(node.desc)) {
                    InsnList insn = new InsnList();
                    insn.add(new VarInsnNode(Opcodes.ALOAD, 0)); // this
                    insn.add(new VarInsnNode(Opcodes.ALOAD, 1)); // public key
                    insn.add(new VarInsnNode(Opcodes.ALOAD, 2)); // modulus
                    /* decrypt */
                    insn.add(new MethodInsnNode(Opcodes.INVOKESTATIC, methodOverride, "C1", "(Ljava/math/BigInteger;Ljava/math/BigInteger;Ljava/math/BigInteger;)Ljava/math/BigInteger;", false));
                    insn.add(new VarInsnNode(Opcodes.ASTORE, 3));
                    insn.add(new InsnNode(Opcodes.ACONST_NULL));
                    insn.add(new VarInsnNode(Opcodes.ALOAD, 3));
                    LabelNode labelNode = new LabelNode();
                    insn.add(new JumpInsnNode(Opcodes.IF_ACMPEQ, labelNode));
                    insn.add(new VarInsnNode(Opcodes.ALOAD, 3));
                    insn.add(new InsnNode(Opcodes.ARETURN));
                    insn.add(labelNode);
                    node.instructions.insert(insn);
                }
            }
        });
    }
}
